import 'dart:convert';

import 'package:flutter_demo/core/common/utils/common_utils.dart';
import 'package:flutter_demo/core/common/values/server.dart';
import 'package:flutter_demo/ui/pages/refresh/list_page_state.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

class ListPageController extends SuperController<ListPageState> {
  //是否滚动
  final isScrolled = Rx<bool>(false);
  //是否成功加载完数据
  final isSucLoad = false.obs;
  final refreshController = RefreshController();

  Future<void> gePageList({bool refresh = false}) async {
    logger.i("gePageList 加载数据");
    final cacheData = box.read<Map<String, dynamic>>(CACHE_HOME_FOUND_DATA);
    //box.write(CACHE_HOME_FOUND_DATA, newData.toJson());
    if (cacheData == null || refresh) {
      var map = jsonDecode(
          "{\"blocks\":[{\"blockCode\":\"1\"},{\"blockCode\":\"2\"},{\"blockCode\":\"3\"},{\"blockCode\":\"4\"},{\"blockCode\":\"5\"},{\"blockCode\":\"6\"},{\"blockCode\":\"7\"},{\"blockCode\":\"8\"},{\"blockCode\":\"9\"},{\"blockCode\":\"10\"}]}");
      isSucLoad.value = true;
      change(ListPageState.fromJson(map), status: RxStatus.success());
    }
  }

  Future<void> loadMore() async {
    if (GetUtils.isNullOrBlank(state) == true) {
      //第一页
      await gePageList(refresh: true);
      //取消显示底部加载中图片
      refreshController.loadComplete();
    } else {
      ListPageState? a = state;
      var k = a!.blocks.length + 1;
      var map = jsonDecode("{\"blockCode\":\"$k\"}");
      Blocks b = Blocks.fromJson(map);
      a.blocks.add(b);
      //refreshController.loadNoData();
      logger.i("加载。。。。。");
      change(a, status: RxStatus.success());
      //if (!refreshController.isLoading && !refreshController.isRefresh) {}
      //Future.delayed(Duration(milliseconds: 1000), () {});
    }
  }

  //刷新过期时间
  int expirationTime = -1;

  @override
  void onDetached() {
    Get.log('onDetached');
  }

  @override
  void onInactive() {
    // TODO: implement onInactive
    Get.log('onInactive');
  }

  @override
  void onPaused() {
    // TODO: implement onPaused
    Get.log('onPaused');
  }

  @override
  void onResumed() {
    //第一次初始化， 和回退到本页面调用
    Get.log('onResumed');
    // TODO: implement onResumed
    if (expirationTime > 0) {
      if (DateTime.now().millisecondsSinceEpoch > expirationTime) {
        //当前时间大于失效时间 刷新
        Get.log("首页刷新时间到期，重新获取数据");
        gePageList(refresh: true);
      }
    }
  }

  @override
  void onReady() {
    logger.i('onReady');
    super.onReady();
    gePageList(refresh: true);
  }

  @override
  void onInit() {
    logger.e("onInit--");
    super.onInit();
    gePageList(refresh: true);
  }
}
